package com.atguigu.day06;

import com.atguigu.beans.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/4/7
 * 该案例演示了自定义Watermark的生成策略
 */
public class Flink07_Watermark_Custom {
    public static void main(String[] args) throws Exception {
        //TODO 1.指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //TODO 2.设置并行度
        env.setParallelism(1);

        //TODO 3.从指定的网络端口读取数据
        DataStreamSource<String> socketDS = env.socketTextStream("hadoop102", 8888);
        //TODO 4.对读取的数据进行类型转换   String->WaterSensor
        SingleOutputStreamOperator<WaterSensor> wsDS = socketDS.map(new WaterSensorMapFunction());
        //TODO ***指定Watermark的生成策略并提取事件时间字段***
        SingleOutputStreamOperator<WaterSensor> withWatermarkDS = wsDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        //指定Watermark的生成策略是单调递增(元素事件时间直接生成Watermark，不需要考虑乱序--减乱序程度)
                        //.<WaterSensor>forMonotonousTimestamps()
                        //.<WaterSensor>forBoundedOutOfOrderness(Duration.ofMillis(3))
                        .forGenerator(
                                new WatermarkGeneratorSupplier<WaterSensor>() {
                                    @Override
                                    public WatermarkGenerator<WaterSensor> createWatermarkGenerator(Context context) {
                                        return new MyGene<>(5);
                                    }
                                }
                        )
                        //提取事件时间字段
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor ws, long recordTimestamp) {
                                        return ws.getTs();
                                    }
                                }
                        )

        );

        //TODO 5.按照传感器的id进行分组
        KeyedStream<WaterSensor, String> keyedDS = withWatermarkDS.keyBy(WaterSensor::getId);
        //TODO 6.开窗---处理时间滚动窗口
        WindowedStream<WaterSensor, String, TimeWindow> windowDS
                = keyedDS.window(TumblingEventTimeWindows.of(Time.milliseconds(10)));
        //TODO 7.对窗口中数据进行处理---process
        SingleOutputStreamOperator<String> processDS = windowDS.process(
                new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WaterSensor, String, String, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long count = elements.spliterator().estimateSize();
                        String windowStart = DateFormatUtils.format(context.window().getStart(), "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(context.window().getEnd(), "yyyy-MM-dd HH:mm:ss.SSS");
                        out.collect("key=" + s + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());
                    }
                }
        );
        //TODO 8.打印输出
        processDS.print();
        //TODO 9.提交作业
        env.execute();
    }
}

class MyGene<T> implements WatermarkGenerator<T>{
    long maxTx ;
    long delayTx ;

    public MyGene( long delayTx){
        this.delayTx = delayTx;
    }
    @Override
    public void onEvent(T event, long eventTimestamp, WatermarkOutput output) {
        maxTx =  Math.max(maxTx,eventTimestamp);
        output.emitWatermark(new Watermark(maxTx - delayTx - 1));
    }

    @Override
    public void onPeriodicEmit(WatermarkOutput output) {
    }
}
